package cn.b504.qpcr.impls;

import cn.b504.qpcr.entity.AjaxResult;
import cn.b504.qpcr.entity.ErrorCode;
import cn.b504.qpcr.entity.User;
import cn.b504.qpcr.interfaces.UserService;
import cn.b504.qpcr.utils.Utils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserImpl implements UserService {
  @Override
  public AjaxResult getUserLists() {
    List<User> userList = Utils.getUserList();
    if (userList == null) {
      return AjaxResult.error(ErrorCode.FILE_NOT_FOUND, "服务器文件错误");
    }

    for (User user : userList) {
      user.setPassword(null);
    }
    return AjaxResult.ok(userList);
  }

  @Override
  public AjaxResult login(User user) {
    String username = user.getUsername();
    String password = Utils.hash(user.getPassword());
    if (username == null || password.isEmpty()) {
      return AjaxResult.error(ErrorCode.REQUEST_PARAM_ERROR, "请求参数错误");
    }

    List<User> userList = Utils.getUserList();
    if (userList == null) {
      return AjaxResult.error(ErrorCode.FILE_NOT_FOUND, "服务器文件错误");
    }

    for (User _user : userList) {
      if (username.equals(_user.getUsername()) && password.equals(_user.getPassword())) {
        int userExpires = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        int expires = Integer.parseInt(_user.getExpires().replaceAll("-", ""));
        if (userExpires > expires) {
          return AjaxResult.error(ErrorCode.USER_EXPIRES, "用户已过期");
        }
        _user.setPassword("");
        return AjaxResult.ok(_user);
      }
    }
    return AjaxResult.error(ErrorCode.USER_NOT_FOUND, "用户名或密码错误");
  }

  @Override
  public AjaxResult addNewUser(User user) {
    String username = user.getUsername();
    if (username == null) {
      return AjaxResult.error(ErrorCode.REQUEST_PARAM_ERROR, "请求参数错误");
    }

    List<User> userList = Utils.getUserList();
    if (userList == null) {
      return AjaxResult.error(ErrorCode.FILE_NOT_FOUND, "服务器文件错误");
    }

    Set<String> set = new HashSet<>();
    for (User _user : userList) {
      if (username.equals(_user.getUsername())) {
        return AjaxResult.error(ErrorCode.USER_NAME_REPEAT, "用户名重复");
      }
      set.add(_user.getId());
    }

    for (int i = 1; i < 1000; i++) {
      String id = Utils.padStart(String.valueOf(i), 3, "0");
      if (set.contains(id)) {
        continue;
      }
      user.setId(id);
      user.setPassword(Utils.hash(user.getPassword()));
      userList.add(i - 1, user);
      return updateAndClearPassword(userList, "增加用户失败");
    }
    return AjaxResult.error(ErrorCode.USER_OVER_LIMIT, "用户数量超限");
  }

  @Override
  public AjaxResult modifyUser(User user) {
    String id = user.getId();
    String username = user.getUsername();
    if (username == null || id == null) {
      return AjaxResult.error(ErrorCode.REQUEST_PARAM_ERROR, "请求参数错误");
    }

    List<User> userList = Utils.getUserList();
    if (userList == null) {
      return AjaxResult.error(ErrorCode.FILE_NOT_FOUND, "服务器文件错误");
    }

    for (User _user : userList) {
      if (username.equals(_user.getUsername()) && !id.equals(_user.getId())) {
        return AjaxResult.error(ErrorCode.USER_NAME_REPEAT, "用户名重复");
      }
    }

    for (User _user : userList) {
      if (id.equals(_user.getId())) {
        _user.setUsername(username);
        _user.setPortrait(user.getPortrait());
        _user.setExpires(user.getExpires());
        _user.setRole(user.getRole());
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
          _user.setPassword(Utils.hash(user.getPassword()));
        }
        return updateAndClearPassword(userList, "修改用户失败");
      }
    }
    return null;
  }

  @Override
  public AjaxResult deleteUser(String id) {
    if (id == null) {
      return AjaxResult.error(ErrorCode.REQUEST_PARAM_ERROR, "请求参数错误");
    }

    List<User> userList = Utils.getUserList();
    if (userList == null) {
      return AjaxResult.error(ErrorCode.FILE_NOT_FOUND, "服务器文件错误");
    }

    for (User _user : userList) {
      if (id.equals(_user.getId())) {
        userList.remove(_user);
        return updateAndClearPassword(userList, "删除用户失败");
      }
    }
    return null;
  }

  private AjaxResult updateAndClearPassword(List<User> userList, String errorMessage) {
    if (Utils.updateUserList(userList)) {
      userList = Utils.getUserList();
      if (userList == null) {
        return AjaxResult.error(ErrorCode.FILE_NOT_FOUND, "服务器文件错误");
      }
      for (User user : userList) {
        user.setPassword(null);
      }
      return AjaxResult.ok(userList);
    }
    return AjaxResult.error(ErrorCode.FAIL, errorMessage);
  }
}
